import os
import shutil
import requests


class FileHandler:
    def __init__(self, webhook_url):
        self.webhook_url = webhook_url

    def _send_feishu_message(self, message):
        try:
            headers = {
                'Content-Type': 'application/json'
            }
            data = {
                'msg_type': 'text',
                'content': {
                    'text': message
                }
            }
            response = requests.post(self.webhook_url, json=data, headers=headers)
            response.raise_for_status()
        except Exception as e:
            print(f'发送飞书消息失败: {e}')

    def rename_files(self, folder_path):
        try:
            folder_name = os.path.basename(folder_path)
            for filename in os.listdir(folder_path):
                file_path = os.path.join(folder_path, filename)
                if os.path.isfile(file_path):
                    if not filename.startswith(folder_name + '_'):
                        new_filename = folder_name + '_' + filename
                        new_file_path = os.path.join(folder_path, new_filename)
                        os.rename(file_path, new_file_path)
            self._send_feishu_message(f'文件夹 {folder_path} 内的文件重命名成功。')
        except Exception as e:
            self._send_feishu_message(f'文件夹 {folder_path} 内的文件重命名失败: {e}')

    def move_files(self, source_folder, target_folder, num_files=2):
        try:
            # source files     
            sorted_files = sorted(
                [x for x in os.listdir(source_folder) if os.path.isfile(os.path.join(source_folder, x))])
            today_files = []
            for filename in sorted_files[:num_files]:
                source_file_path = os.path.join(source_folder, filename)
                try:
                    traget_dir = filename.split('_')[0]
                except:
                    traget_dir = 'other'
                print(traget_dir)
                new_target_folder = os.path.join(target_folder, traget_dir)
                if not os.path.exists(new_target_folder):
                    os.makedirs(new_target_folder)
                target_file_path = os.path.join(new_target_folder, filename)
                shutil.move(source_file_path, target_file_path)
                today_files.append(filename)
            today_file_name_str = "\n".join(today_files)
            if len(today_files) < num_files:
                msg = f'从 {source_folder} 移动 {num_files} 个文件到 {new_target_folder} 失败: 源文件夹中文件数量不足 {num_files} 个, 程序仍会执行:\n{today_file_name_str}'
                self._send_feishu_message(msg)
                return msg
            msg = f'从 {source_folder} 移动 {num_files} 个文件到 {new_target_folder} 成功:\n{today_file_name_str}'
        except Exception as e:
            new_target_folder = "other"
            msg = f'从 {source_folder} 移动 {num_files} 个文件到 {new_target_folder} 失败: {e}'
        self._send_feishu_message(msg)
        return msg